<template>
  <div class="review-container">
    <div class="review-tit">
      <div class="left-tit">
        <span>评论区</span>
        <div class="sort-actions">
          <div class="sort-button"  :class="{ cur: typeId === 2 }" @click="changeType(2)">最热</div>
          <div class="sort-div">|</div>
          <div class="sort-button"  :class="{ cur: typeId === 1 }" @click="changeType(1)">最新</div>
        </div>
      </div>
      <div class="right-num">共<span>{{total}}</span>条回复</div>
    </div>
    <div class="user-content">
      <!-- 顶部添加评论 -->
      <div class="top-insert">
        <el-input
          v-model="addReviewData.content"
          style="font-size: 14px"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          :placeholder="commentSetting?.remarksPrompt"
          rows="4"
          show-word-limit
          maxlength="1000"
        />
        <div class="but-box">
          <el-button class="submit-but" type="primary" @click="submitComment"
            >发布</el-button
          >
        </div>
      </div>
      <!-- 滚动加载评论 -->
      <div
        v-infinite-scroll="loadReview"
        class="comment-list"
      >
        <li
          v-for="item in reviewData.filter(item => item.notFilter || !tempId.includes(item.id))"
          :key="item.id"
          class="infinite-list-item"
        >
          <div class="top-info">
            <div class="name"><span>{{ item.username }}</span></div>
          </div>
          <div class="bottom-review">
            <div class="review-content">{{ item.content }}</div>
            <div class="review-time">
              <div class="time">
                {{ dayjs(item.createTime).format("YYYY-MM-DD HH:mm") }}
              </div>
              <div class="right-num" @click="handleReply(item,false)" v-if="commentSetting?.allowRemark">
                <el-icon><ChatDotSquare /></el-icon>{{item.childCount}}
              </div>
              <div class="show-replay" type="primary" v-if="commentSetting?.allowRemark" @click="showReplay(item,true)">
                回复
              </div>
            </div>
          </div>
          <!-- 子评论显示区 -->
          <div id="replies" v-if="item.children && item.children.length > 0 && commentSetting?.allowRemark">
            <li
              class="kid-li infinite-list-item"
              v-for="kid in item.children"
              
              :key="kid.id"
            >
              <div class="top-info">
                <div class="name"><span>{{ kid.username }}</span><div v-if="kid.pid != item.id">&nbsp;回复：<span>{{kid.pidUsername}}</span></div></div>
              </div>
              <div class="bottom-review">
                <div class="review-content">{{ kid.content }}</div>
                <div class="review-time">
                  <div class="time">
                    {{ dayjs(kid.createTime).format("YYYY-MM-DD HH:mm") }}
                  </div>
                  <div class="show-replay" type="primary" @click="showReplay(kid,false,item.id)">
                    回复
                  </div>
                </div>
              </div>
            </li>
            <div class="bottom-options">
              <span @click="showMore(item)" v-if="item.childCount > item.children.length">展开更多<el-icon><ArrowDown /></el-icon></span>
              <span @click="hideMode(item.id)">收起<el-icon><ArrowUp /></el-icon></span>
            </div>
          </div>
          <!-- 弹出回复框 -->
          <div id="reply-container">
            <div class="replyEdit" v-if="showReplayFlag && item.id == reviewId" >
              <el-input
                v-model="addKidReviewData.content"
                style="font-size: 14px"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                :placeholder="addKidReviewData?.newPrompt"
                rows="4"
                maxlength="1000"
                autofocus
              />
              <!-- <div class="replyImgList replyUploadImgList" style="position: relative" >
                <div class="addImg" style="display: none; position: relative; z-index: 1" >
                  <input type="file" accept="image/*" />
                </div>
              </div> -->
              <div class="replyEditBtnGroup" style="position: relative">
                <!-- <div class="imgUpload" style="position: relative; z-index: 1">
                  <input type="file" accept="image/*" />
                </div> -->
                <el-button @click="cancelSubmit">取消</el-button>
                <el-button class="submit-but" type="primary" @click="submitComment">发布</el-button>
              </div>
            </div>
          </div>
        </li>
      </div>
    </div>
    <SlideVerify @onSuccess="handleLogin" v-model:show="loginVerifyShow" />
    <!-- <el-button @click="loginVerifyShow = true">显示验证</el-button> -->
    <!-- 安全扫描  -->
    <!-- <el-button @click="safeScan">显示安全扫描</el-button> -->

  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { selectfunction } from "@/api/setting";
import { useStore } from 'vuex'
import { getToken } from '@ruifox-cms/utils'
import { ElMessage } from "element-plus";
import { ChatDotSquare, ArrowDown, ArrowUp } from "@element-plus/icons-vue";
import {
  selectPageByPidCommentRemarks,
  selectPageByChildIdCommentRemarks,
  insertCommentRemarks,
  cancelLimitedCommentRemarks
 } from "@/api/review";
import { useRouter } from "vue-router";
import dayjs from "dayjs";
import { myDebounce } from '@/utils/tools'
// import { createContentScanTask } from '@/api/safe'

const store = useStore();
const hasToken = ref(!!getToken())
const router = useRouter();

const props = defineProps({
  commentId: {
    type: Number,
    default: 0
  },
})
const commentId = ref(props.commentId)
// const commentIdLoading = ref(false);
const loginVerifyShow = ref(false)

//内容上传前扫描 暂未启用 等待对接2.0
// const safeScan = async () => {
//   const res = await createContentScanTask({
//     content: "殴打，吸毒，毒品，小日本，赌博，林彪，文革，四人帮反动、独裁、革命、暴乱杀人、爆炸、袭击、枪击大麻、海洛因、赌场、偷窃", 
//     storeIds: []
//   })
  
// }

//人机验证通过，允许用户继续评论
const handleLogin = async () => {
  try {
    await cancelLimitedCommentRemarks({userId: store.state.base.userInfo.id})
  } catch (error) {
    console.log("出错了",error);
  }
}
//获取留言设置
const commentSetting = ref()
const getCommentSetting = async () => {
  const res = await selectfunction()
  commentSetting.value = res.data
  console.log("留言设置",commentSetting.value);
  
}
getCommentSetting()

//提交评论
const addReviewData = reactive({
  commentId: props.commentId,
  content: "",
  images: "",
  pid: 0,
  userId: 0,
  username: ""
})

//提交子评论
const addKidReviewData = reactive({
  commentId: props.commentId,
  content: "",
  images: "",
  pid: 0,
  userId: 0,
  username: "",
  pidUsername: ""
})
const addKidId = ref(0)  //是否是子评论
const reviewId = ref(0)  //评论id
const tempId = ref([])  //临时评论id，用于控制本地虚拟数据不和实际数据重复
const addReview = async () => {
  let thisReview = {}
  if(addKidId.value == 0){
    thisReview = addReviewData
  } else {
    thisReview = addKidReviewData
  }
  
  //评论不为空
  if (!thisReview.content.trim()) {
    ElMessage({
      showClose: true,
      message: `评论不能为空` ,
      type: 'warning'
    })
    return
  }
  //判断当前是否需要登录
  if (commentSetting.value.needLogin == true) {
    if (!hasToken.value) {
      ElMessage({
        showClose: true,
        message: '请先登录',
        type: 'warning'
      })
      setTimeout(() => {
        router.push('/comment/user/commentFormList')
      }, 1000) // 延迟跳转登录页
    }
    thisReview.username = store.state.base.userInfo.name
    thisReview.userId = store.state.base.userInfo.id
    thisReview.commentId = commentId.value
  }
  try {
    const res = await insertCommentRemarks(thisReview);
    if (res.code === 20000) {
      ElMessage.success("评论成功");
      // 虚拟数据的id更改为后端返回的id
      thisReview.id = res.data
      thisReview.notFilter = true
      tempId.value.push(res.data)
      let newReview = { ...thisReview };
      //如果不是增加子评论 手动添加虚拟数据到第一条 否则增加到对应子评论第一条
      if(addKidId.value != 0){
        const targetItem = reviewData.value.find(item => item.id === addKidId.value);
        if (!Array.isArray(targetItem.children)) {
          targetItem.children = [];
        }
        targetItem.children.splice(0, 0, newReview);
        targetItem.childCount++
      } else {
        reviewData.value.splice(0, 0, newReview)
      }
      total.value++
      thisReview.content = ""
    } 
  } catch (error) {
    ElMessage.error("评论失败");
    console.log("评论失败",error);
    loginVerifyShow.value = true;
  }
}

//提交评论防抖
const submitComment = myDebounce(addReview, 500)

//展示子评论
const kidQuery = ref({
  currentPage: 1,
  pageSize: 5,
  commentId: "",
  pid: ""
})
const handleReply = async (element,isShowComment) => {
  if(!isShowComment && !element.isShowComment){
    element.isShowComment = true
  } else if(!isShowComment && element.isShowComment){
    return
  }
  if (element.childCount > 0) {
    kidQuery.value.pid = element.id 
    if (element.currentPage) {
      kidQuery.value.currentPage = element.currentPage
      console.log(111);
      
    }
    kidQuery.value.commentId = commentId.value
    const res = await selectPageByChildIdCommentRemarks(kidQuery.value);
    if (res.code == 20000) {
      //将请求数据添加至本地
      if (!Array.isArray(element.children)) {
        element.children = []
      }
      element.children.push(...res.data.list)
      //如果之前没有请求过子评论，其currentPage设置为1
      if(!element.currentPage){
        element.currentPage = 1
      }
    } else {
      ElMessage.error("获取回复失败")
    }
  }
}

//展示更多子评论
const showMore = async (element) => {
  if(element){
    element.currentPage++
    await handleReply(element,true)
  }
}
//收起子评论
const hideMode = (id) => {
  if (id) {
    const targetItem = reviewData.value.find(item => item.id === id);
    targetItem.children = []
    targetItem.currentPage = ""
    targetItem.isShowComment = false
  }
}
//动态显示评论输入框
const showReplayFlag = ref(false)
const showReplay = (item,notPid,iskid) => {
  //根据回复人判断当前显示人
  addKidReviewData.newPrompt = "回复 " + item.username
  addKidReviewData.pid = item.id
  addKidReviewData.pidUsername = item.username
  
  //如果是一级评论，显示回复框，且回复框Id为当前评论Id；
  //如果是子评论，回复框Id为其父评论Id，显示效果还是在父评论下第一条虚拟新增数据
  if(notPid == true){
    reviewId.value = item.id
    addKidId.value = item.id
  }
  else if(iskid) {
    reviewId.value = iskid
    addKidId.value = iskid
  } else {
    addKidId.value = 0
  }
  showReplayFlag.value = true
}

//取消提交评论
const cancelSubmit = () => {
  addKidReviewData.content = ""
  reviewId.value = 0
  showReplayFlag.value = false
}

//分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)
const reviewData = ref([])

// 分页获取评论列表
const getReview = async (isLoadMore = false) => {
  if (loading.value) return
  loading.value = true
 
  try {
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      commentId: commentId.value,
      type: typeId.value
    }
    
    const res = await selectPageByPidCommentRemarks(params)
    if (isLoadMore) {
      reviewData.value.push(...res.data.list)
    } else {
      reviewData.value = res.data.list
    }
    total.value = res.data.total
    hasMore.value = reviewData.value.length < total.value
  } catch (error) {
    console.error('获取评论数据失败:', error)
    ElMessage.error('获取评论数据失败')
  } finally {
    loading.value = false
  }
}

//获取评论
const loadReview = async () => {
  if (!hasMore.value || loading.value) return
  currentPage.value++
  getReview(true)
}
//评论排序方式
const typeId = ref(2)
const changeType = (id) => {
  //如果排序方式改变，清楚数据重新请求
  if (typeId.value != id) {
    typeId.value = id;
    currentPage.value = 1
    reviewData.value = []
    // console.log("currentPage.value",currentPage.value);
    getReview()
  }
}

watch(
  () => props.commentId,
  (newCommentId) => {
    commentId.value = newCommentId;
    getReview(); // 在 commentId 更新后调用
  },
  { immediate: true } // 立即执行一次，确保初始值也能触发
);

onMounted(() => {
  if (commentId.value) {
    getReview();
  }
  // getReview()
})
</script>
<style scoped lang="scss">
.review-container {
  margin-top: 40px;
  margin-bottom: 20px;
  .user-content {
    margin-top: 10px;
    .but-box {
      margin-top: 10px;
      display: flex;
      justify-content: end;
    }
  }
}
.review-tit {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .left-tit {
    display: flex;
    /* align-items: end; */
    span{
      font-size: 24px;
      color: $mainColor;
    }
    .sort-actions{
      margin-left: 15px;
      display: flex;
      align-items: center;
      color: #999;
      .sort-button{
        font-size: 14px;
        margin: 0 8px;
        cursor: pointer;
        &.cur{
          color: $black;
        }
        &:hover{
          color: $mainColor;
        }
      }
    }
  }
  .right-num {
    font-size: 16px;
    color: $black_2;
    span {
      font-size: 18px;
      color: $black;
      margin: 0 5px;
    }
  }
}
/* 评论样式设置 */
.comment-list {
  margin-top: 10px;
  margin-bottom: 40px;
  min-height: 400px;
}
.infinite-list-item {
  margin-top: 15px;
  padding: 0 0 15px;
  border-bottom: 1px solid $borderColor;
  .top-info {
    display: flex;
    justify-content: space-between;
    .name {
      font-size: 14px;
      color: #666;
      display: flex;
      span {
        font-size: 16px;
        color: $black_2;
      }
    }
  }
  .bottom-review {
    margin-top: 10px;
    .review-content {
      font-size: 18px;
      color: $black;
    }
    .review-time {
      margin-top: 10px;
      font-size: 14px;
      line-height: 14px;
      color: #888;
      display: flex;
      align-items: center;
      .time {
        margin-right: 15px;
      }
      .right-num {
        margin-right: 15px;
        cursor: pointer;
        i {
          margin-right: 5px;
        }
        &:hover {
          color: $mainColor;
        }
      }
      .show-replay {
        color: #666;
        cursor: pointer;
        &:hover {
          color: $mainColor;
        }
      }
    }
  }
  #replies{
    margin-left: 40px;
    margin-top: 20px;
    padding: 15px;
    border-radius: 5px;
    background: $homeBgColor;
    .kid-li{
      margin-top: 12px;
      padding-bottom: 12px;
      &:first-child {
        margin-top: 0;
      }
    }
    .bottom-options{
      display: flex;
      margin-top: 5px;
      font-size: 14px;
      color: #666;
      align-items: center;
      span{
        margin-right: 20px;
        cursor: pointer;
        &:hover{
          color: $mainColor;
        }
      }
      i{
        margin-left: 5px;
      }
    }
  }
  .replyEdit {
    margin-top: 10px;
    margin-left: 40px;
    .replyEditBtnGroup {
      margin-top: 10px;
      display: flex;
      justify-content: end;
    }
  }
}
/* 响应式 */
@media (max-width: 960px) {
  .review-container{
    margin-top: 20px;
  }
  .review-tit .left-tit span{
    font-size: 18px;
  }
  .infinite-list-item {
    margin-top: 12px;
    padding-bottom: 12px;
  }
}
</style>
